package cn.dgut.springboot.mini.controller;

import cn.dgut.springboot.mini.dto.CustomerDTO;
import cn.dgut.springboot.mini.entity.Customer;
import cn.dgut.springboot.mini.exception.CustomerException;
import cn.dgut.springboot.mini.repo.CustomerRepo;
import cn.dgut.springboot.mini.transfer.CustomerDtoTransfer;
import cn.dgut.springboot.mini.utils.UpdateTool;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 周智涛
 * @Description
 * @date 2019/12/12 11:22
 */
@RestController
@RequestMapping("/customer")
public class CustomerController {

    @Autowired
    private CustomerRepo customerRepo;


    @GetMapping("{id}")
    public Customer findCustomerById(@PathVariable Long id){

        return customerRepo.findById(id).orElseThrow(()-> new RuntimeException(
            "Customer [customerId="+id+"] can't be found"
        ));

    }

    @PostMapping
    public Customer save(@RequestBody Customer customer) {

        try {
            return customerRepo.save(customer);
        }catch (Exception e){
            throw new RuntimeException("添加失败");
        }
    }

    @PutMapping
    public Customer update(@RequestBody Customer customer) {

       return customerRepo.findById(customer.getId()).map(customer1->{

           //前端没法全量回传所有属性的情况
           UpdateTool.copyNullProperties(customer1,customer);
           try {
               return customerRepo.save(customer);
           }catch (Exception e){
               throw new RuntimeException("更新失败");
           }
        }).orElseThrow(()->new RuntimeException("Customer [customerId="+customer.getId()+"] can't be found"));

    }



    @DeleteMapping("/{id}")
    public ResponseEntity delete(@PathVariable Long id) {

        return customerRepo.findById(id).map(customer -> {
            try {
                customerRepo.delete(customer);
                return ResponseEntity.ok().build();
            }catch (Exception e){
                throw new RuntimeException("删除失败");
            }
        }).orElseThrow(()->new RuntimeException("Customer [customerId="+id+"] can't be found"));

    }

    /**
     * 动态查询分页排序接口
     * @param customerDTO
     * @return
     */
    @GetMapping("/search")
    public List<Customer> search(@RequestBody CustomerDTO customerDTO){

        PageRequest pageRequest= CustomerDtoTransfer.getPageRequest(customerDTO);
        Specification specification= CustomerDtoTransfer.getSpecification(customerDTO);
        Page page = customerRepo.findAll(specification, pageRequest);

        return page.getContent();

    }


    @ExceptionHandler(CustomerException.class)
    public Map exception(CustomerException ex){

        Map<String,String> map=new HashMap<>();
        map.put("erroeMessage",ex.getMessage());
        map.put("code","500");
        return map;
    }


}
